// 构建一个功能更强大的守卫，只允许具有特定角色的用户访问
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Roles } from './roles.decorator';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get(Roles, context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    console.log('request', request.body);
    const user = request.body.user;
    return matchRoles(roles, user);
  }
}
function matchRoles(roles: string[], userRoles: string): boolean {
  if (roles.includes(userRoles)) {
    return true;
  } else {
    return false;
  }
}
